﻿using System;

namespace TableTop.TestConsoleApplication.Network
{
    public class ServerHost
        : IDisposable
    {
        private AppDomain ServerDomain = null;
        private ProviderServer psServer = null;

        public ServerHost()
        {
            Type tpProviderServerType = typeof(ProviderServer);

            this.ServerDomain = AppDomain.CreateDomain("TestServiceHostDomain");
            this.ServerDomain.UnhandledException += new UnhandledExceptionEventHandler(ServerDomain_UnhandledException);
            psServer = (ProviderServer) this.ServerDomain.CreateInstanceAndUnwrap(tpProviderServerType.Assembly.FullName,
                                                                                  tpProviderServerType.FullName);

        }

        private void ServerDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exc = null;
            exc = (Exception) e.ExceptionObject;
            Console.WriteLine(exc.ToString());
        }

        public void Listen()
        {
            this.psServer.Listen();
        }

        public void Close()
        {
            this.psServer.Close();
        }

        #region IDisposable Members

        public void Dispose()
        {
            AppDomain.Unload(this.ServerDomain);
        }

        #endregion
    }
}
